// pages/my/chatroom/chatrrom.js

const TIM = require("../../../components/tim/tim-wx");
const util = require('../../../utils/util');
const requestUtil = require('../../../utils/request');
const api = require('../../../config/api');
const timConst = require("../../../config/const");
const app = getApp();

import {
  caculateTimeago
} from '../../../components/tim/tui/base/common'

let tim = wx.$TIM;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIMlogin: false, // im是否已登录
    conversationList: [], // 会话列表
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    tim.setLogLevel(0);
    // tim.registerPlugin({
    //   'tim-upload-plugin': TIMUploadPlugin
    // });
    this.im_on();
  },

  onShow: function () {
    let _this = this;
    _this.getConversationList();
  },

  // ListTouch触摸开始
  ListTouchStart(e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },

  // ListTouch计算方向
  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
    })
  },

  // ListTouch计算滚动
  ListTouchEnd(e) {
    if (this.data.ListTouchDirection == 'left') {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },

  /**
   * 获取会话列表
   * 
   * 获取详细会话信息getConversationProfile
   */
  getConversationList: function () {
    let _this = this;

    // 获取全量的会话列表
    let promise = tim.getConversationList();
    promise.then(function (imResponse) {
      // 全量的会话列表，用该列表覆盖原有的会话列表
      const conversationList = imResponse.data.conversationList;
      for (let list of conversationList) {
        if (list.conversationID) {
          list.lastMessage.timeago = caculateTimeago(list.lastMessage.lastTime * 1000)
          list.lastMessage.messageForShow = list.lastMessage.messageForShow.slice(0, 15)
        }
      }
      _this.setData({
        conversationList: conversationList
      })
    }).catch(function (imError) {
      // 获取会话列表失败的相关信息
      console.warn('getConversationList error:', imError);
    });
  },

  /**
   * 删除会话
   */
  deleteConversation: function (e) {
    let _this = this;
    wx.showModal({
      content: '确认删除会话？',
      success: (res) => {
        if (res.confirm) {
          util.showToast('删除成功')
          tim.deleteConversation(e.currentTarget.dataset.id)
          setTimeout(() => {
            _this.getConversationList();
          }, 1500)
        }
      },
    })
  },

  /**
   * 跳转到特定对话
   */
  toChat: function (e) {
    console.log('id', e.currentTarget.dataset.id);
    wx.navigateTo({
      url: './room/room?id=' + e.currentTarget.dataset.id,
    })
  },

  /**
   * 监听IM是否启动
   */
  im_on: function () {
    let _this = this;

    console.log('监听IM中-------------------------');

    tim.on(TIM.EVENT.MESSAGE_RECEIVED, (event) => {
      // 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
      // event.name - TIM.EVENT.MESSAGE_RECEIVED
      // event.data - 存储 Message 对象的数组 - [Message]
      console.log('----------收到推送的单聊、群聊、群提示、群系统通知的新消息', event.data)
      console.log('2');
      _this.getConversationList();
    })
  },

})